﻿'*
'*  TweetMyPC
'*  Copyright (C) 2010 TweetMyPC Team
'*
'*  This program is free software; you can redistribute it and/or modify
'*  it under the terms of the Microsoft Public License as published by
'*  Microsoft Corporation and available in 2010.
'*
'*  This program is distributed in the hope that it will be useful,
'*  but WITHOUT ANY WARRANTY; without even the implied warranty of
'*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'*  Microsoft Public License for more details.
'*
'*  You are not allowed to change/add/remove this Header, except adding
'*  to the Programmers list below or if the autor allowed you to do so!
'*
'*  You should have received a copy of the Microsoft Public License along
'*  with this program-code download; if not see the license page at http://tweetmypc.codeplex.com.
'*
'* Creator of this file: Shoban Kumar (shobankr@gmail.com)
'*
'* COPYRIGHT:   See License in the top level directory of the sourcecode or http://tweetmypc.codeplex.com
'* PROJECT:     TweetMyPC
'* FILE:        ./frmTweetMyPC.vb
'* PROGRAMMERS: Shoban Kumar (shobankr@gmail.com)
'*              Kushal (http://twitter.com/kushal855)
'*              Nicolas (http://twitter.com/nt_)
'*              Stefan Ludowicy / BasisBit (hp.stefan@gmail.com)
'*              Gio d'Amelio(giodamelio@gmail.com)
'*              {add your name here if you changed the code and want to distribute it}
'*

Imports Microsoft.Win32
Imports System.Xml
Imports System.Text
Imports System.Environment
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Net
Imports System.Threading
Imports System.IO
Imports System.Net.Mail
Imports Newtonsoft.Json

Public Class frmTweetMyPc

#Region "Definitions"
    Public con As New OleDb.OleDbConnection
    Public cmd As New OleDb.OleDbCommand
    Public databasePath As String
    Public workingFolder As String
    Private Declare Sub GlobalMemoryStatus Lib "kernel32" (ByRef lpBuffer As MEMORYSTATUS)
    Shared sTotalPhys As String
    Shared sAvailPhys As String
    Shared sTotalVirtual As String
    Shared sAvailVirtual As String
    Shared sSysOS As String
    Shared sSysUser As String
    Shared sSysDomain As String
    Shared sSysMachine As String
    Dim dwnloadThread As Thread
    Dim printThread As Thread
    Dim tw As New TwitterVB2.TwitterAPI
#End Region

    Private Structure MEMORYSTATUS
        Dim dwLength As Integer
        Dim dwMemoryLoad As Integer
        Dim dwTotalPhys As Integer
        Dim dwAvailPhys As Integer
        Dim dwTotalPageFile As Integer
        Dim dwAvailPageFile As Integer
        Dim dwTotalVirtual As Integer
        Dim dwAvailVirtual As Integer
    End Structure

    Private Sub chkStartAutomatic_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkStartAutomatic.CheckedChanged
        If chkStartAutomatic.Checked = True Then
            My.Settings.AutomaticStart = True
            Dim regKey As RegistryKey
            regKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
            regKey.SetValue(Application.ProductName, Application.ExecutablePath)
            regKey.Close()
        Else
            My.Settings.AutomaticStart = False
            Dim regKey As RegistryKey
            regKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
            regKey.DeleteValue(Application.ProductName)
            regKey.Close()
        End If
    End Sub

    Private Sub tmrTweet_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrTweet.Tick
        tmrTweet.Enabled = False
        If Me.ShowInTaskbar = True Then Exit Sub
        NotifyIcon.Text = "Checking for new tweet..."
        DebugPrintHelper("Status changed to 'checking for new tweet...'")
        If My.Settings.OAuthToken.Trim = "" Then
            DebugPrintHelper("Not connected to twitter account!")
        Else
            CheckForWebConnection()
            'Check for new Tweet 

            Try 'Try Logging in
                tw.AuthenticateWith(My.Resources.ConsumerKey, My.Resources.ConsumerSecret, My.Settings.OAuthToken, My.Settings.OAuthTokenSecret)
            Catch ex As Exception
                DebugPrintHelper("Error : Failed to Login to Twitter with the values supplied. Please check your login details.")
                tmrTweet.Enabled = True
                Exit Sub
            End Try

            Try
                Dim tweetNew As TwitterVB2.TwitterStatus = tw.UserTimeline.Item(0)
                If tweetNew.ID.ToString.Trim <> My.Settings.LastID.Trim Then 'Compare the Tweet ID to check for new tweets
                    My.Settings.LastID = tweetNew.ID.ToString.Trim
                    Dim Tweet As String
                    Tweet = ((tweetNew.Text).Split("##"))(0)
                    Do While Tweet.EndsWith(" ")
                        Tweet = Tweet.Remove(Tweet.Length - 1, 1)
                    Loop
                    DebugPrintHelper("new tweet after trim in tmrTweet.Tick: """ + Tweet + """")
                    tmrTweet.Interval = 7000
                    ProcessTweet(Tweet)
                Else
                    If tmrTweet.Interval = 7000 Then
                        tmrTweet.Interval = 8000
                    ElseIf tmrTweet.Interval = 8000 Then
                        tmrTweet.Interval = 9000
                    ElseIf tmrTweet.Interval = 9000 Then
                        tmrTweet.Interval = 10000
                    ElseIf tmrTweet.Interval = 10000 Then
                        tmrTweet.Interval = 16000
                    Else
                        tmrTweet.Interval = 16000
                    End If
                End If
                DebugPrintHelper("rate-limit-count: " & tw.RateLimit_RemainingHits)
            Catch ex As Exception
                DebugPrintHelper("exception in tmrTweet.Tick when comparing the Tweet ID to check for new tweets or in processing the command (this is the external safety-ring for everything...)")
                DebugPrintHelper(ex.Message)
                tmrTweet.Interval = 16000
                tmrTweet.Enabled = True
                NotifyIcon.Text = "Program activated and waiting for new tweet..."
                DebugPrintHelper("Status changed to 'Program activated and waiting for new tweet...'")
                If Not con.State = ConnectionState.Closed Then con.Close()
                'con.Dispose()
                Exit Sub
            End Try
        End If
        tmrTweet.Enabled = True
        NotifyIcon.Text = "Program activated and waiting for new tweet..."
        DebugPrintHelper("Status changed to 'Program activated and waiting for new tweet...'")
    End Sub

    Private Sub ProcessTweet(ByVal Tweet As String)
        NotifyIcon.Text = "Processing tweet..."
        DebugPrintHelper("Status changed to 'Processing tweet...'")

        Select Case LCase(Tweet)
            Case "abortshutdown"
                SendTweet("Shutdown aborted!")
                System.Diagnostics.Process.Start("shutdown", "-a") 'abort shutdown
            Case "shutdown"
                SendTweet("Turning off my computer")
                System.Diagnostics.Process.Start("shutdown", "-s -f -t 40") 'Shutdown
            Case "logoff"
                SendTweet("Loggin off my computer")
                System.Diagnostics.Process.Start("shutdown", "-l -f -t 40") 'Logoff
            Case "restart"
                SendTweet("Restarting my computer")
                System.Diagnostics.Process.Start("shutdown", "-r -f -t 40") ' Force the system to shutdown
            Case "physical memory"
                ShowMemoryStatus()
                SendTweet(String.Format("Free Physical Memory: {0} from total: {1}", sAvailPhys, sTotalPhys))
            Case "virtual memory"
                ShowMemoryStatus()
                SendTweet(String.Format("Free Virtual Memory: {0} from total: {1}", sAvailVirtual, sTotalVirtual))
            Case "showwindow"
                NotifyIcon.Visible = True
                chkShowinnotifyarea.Checked = True
                Me.ShowInTaskbar = True
                Me.WindowState = FormWindowState.Normal
            Case "os"
                SystemInfo()
                SendTweet(String.Format("OS: {0}", sSysOS))
            Case "help"
                SendTweet("For help please see http://tweetmypc.codeplex.com")
            Case "ip"
                'Code for IP
                Dim ip As IPHostEntry
                ip = Dns.GetHostByName(Dns.GetHostName)
                SendTweet("internal IP Address : " + ip.AddressList(0).ToString + "  external IP Adress: " + GetIpAddress.Trim)
            Case "lock"
                'Lock Workstation
                SendTweet("Locking workstation")
                Process.Start("rundll32.exe", "user32.dll,LockWorkStation")
            Case "standby"
                'Standby
                SendTweet("Setting Workstation to Standby mode")
                Application.SetSuspendState(PowerState.Suspend, True, True)
            Case "hibernate"
                'Hibernate
                SendTweet("Hibernating system")
                Application.SetSuspendState(PowerState.Hibernate, True, True)
            Case "screenshot"
                SendTweet("screenshot doesn't work in this version, but will later - sorry")
                'sendScreenshot()
            Case "getprocesslist"
                getProcessList()
            Case "powerstate"
                Dim messageString As String = _
                    "PowerLineStatus: " & SystemInformation.PowerStatus.PowerLineStatus.ToString & _
                    " & BatteryLevel: " & (SystemInformation.PowerStatus.BatteryLifePercent * 100) & "%" & _
                    " & remaining BatteryTime: " & Math.Round(SystemInformation.PowerStatus.BatteryLifeRemaining / 60, 0).ToString & "min" & _
                    " & charge status: " & SystemInformation.PowerStatus.PowerLineStatus.ToString
                SendTweet(messageString.Trim)
            Case "startscr"
                ToggleScreenSaverActive(True)
                SendTweet("Screensaver started")
            Case "stopscr"
                ToggleScreenSaverActive(False)
                Me.Cursor = New Cursor(Cursor.Current.Handle)
                Cursor.Position = New Point(Cursor.Position.X - 5, Cursor.Position.Y - 105)
                Cursor.Clip = New Rectangle(Me.Location, Me.Size)
                SendTweet("Screensaver stopped")
            Case "ping"
                SendTweet("*waking up..* yes, I am still alive! See http://www.dilbert.com/fast ! ;-)")
            Case "darkscreen"
                darken_change()
                SendTweet("Display turned off.")
            Case "volmute"
                VolMute()
                SendTweet("Volume muted.")
            Case "volunmute"
                VolMute()
                SendTweet("Volume unmuted.")
            Case "volinc"
                For i1 As Integer = 1 To 10
                    VolInc()
                Next i1
                SendTweet("Volume increased.")
            Case "voldec"
                For i1 As Integer = 1 To 10
                    VolDec()
                Next i1
                SendTweet("Volume decreased.")
            Case Else
                splitAndProcess(Tweet)
                runCustomCommands(Tweet)
        End Select
    End Sub

    Public Sub runCustomCommands(ByVal tweet As String)
        Dim splitTweet As String
        splitTweet = tweet.Split(" ")(0)

        NotifyIcon.Text = "Checking for custom command."
        DebugPrintHelper("Status changed to 'Checking for custom command'")
        'con.ConnectionString = _
        '       "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        '       "Data Source=" & databasePath & ";"
        cmd.Connection = con
        Try
            con.Open()
        Catch ex As Exception
            SendTweet("Error opening DB. Please try again.")
        End Try
        cmd.CommandText = "SELECT File FROM CustomCommand WHERE Command ='" + LCase(splitTweet) + "'"
        Dim FilePath As String
        FilePath = cmd.ExecuteScalar()

        If FilePath <> "" Then
            SendTweet("Running custom command.")
            Dim optionsTweet As String
            optionsTweet = tweet.Remove(0, splitTweet.Length)
            Do While optionsTweet.StartsWith(" ") = True
                optionsTweet = optionsTweet.Remove(0, 1)
            Loop
            DebugPrintHelper("RunCustomCommands run this command: """ & FilePath & optionsTweet & """")
            System.Diagnostics.Process.Start(FilePath, optionsTweet)
        End If
        con.Close()
        'con.Dispose()
    End Sub

    Private Sub getProcessList()
        NotifyIcon.Text = "Getting process-list..."
        DebugPrintHelper("Status changed to 'Getting process-list...'")

        If My.Settings.GmailUserName = "" Then
            SendTweet("Email is not configured. Cannot send Process List")
            Exit Sub
        End If

        Dim path As String
        path = workingFolder & "\ListOfProcess.txt"
        Dim ioFile As New StreamWriter(path)
        Dim proc As System.Diagnostics.Process
        For Each proc In System.Diagnostics.Process.GetProcesses
            ioFile.WriteLine(proc.Id & "=>" & proc.ProcessName)
        Next
        ioFile.Close()
        ioFile.Dispose()
        SendEmail(My.Settings.GmailUserName, My.Settings.GmailPassword, path, "Process list by TweetMyPC")
        SendTweet("Process list sent as email.")
    End Sub

    Public Sub splitAndProcess(ByVal tweet As String)
        Dim splitTweet As String '
        splitTweet = LCase(tweet.Split(" ")(0))

        Select Case LCase(splitTweet)

            Case "getfile"
                DebugPrintHelper("jumped into Case getfile")
                'Send file as attachment
                Dim FileLocation As String
                FileLocation = tweet.Remove(0, splitTweet.Length)

                Do While FileLocation.StartsWith(" ") = True
                    FileLocation = FileLocation.Remove(0, 1)
                Loop
                Dim FileName As String = IO.Path.GetFileName(FileLocation)
                DebugPrintHelper("file location seems to be " & FileLocation)
                If My.Settings.GmailUserName <> "" Then
                    DebugPrintHelper("emails seems to be configured!")
                    If FileLocation.EndsWith(".exe") Then
                        DebugPrintHelper("FileLocation seems to end with '.exe' so now delete old stuff in copyto folder and try to copy the file")
                        If File.Exists(workingFolder & "\" & FileName & ".name") Then File.Delete(workingFolder & "\" & FileName & ".name")
                        Try
                            FileCopy(FileLocation, workingFolder & "\" & FileName & ".name")
                            FileName = FileName & ".name"
                        Catch ex As Exception
                            DebugPrintHelper("FileCopy failed with this error:" & ex.Message)
                            SendTweet("Can't send file - check path of file and read-permissions or ask for help at http://tweetmypc.codeplex.com")
                            Exit Sub
                        End Try
                    Else
                        DebugPrintHelper("looks like it doesn't end with '.exe'")
                        If File.Exists(workingFolder & "\" & FileName) Then File.Delete(workingFolder & "\" & FileName)
                        Try
                            FileCopy(FileLocation, workingFolder & "\" & FileName)
                        Catch ex As Exception
                            DebugPrintHelper("FileCopy failed with this error:" & ex.Message)
                            SendTweet("Can't send file - check path of file and read-permissions or ask for help at http://tweetmypc.codeplex.com")
                            Exit Sub
                        End Try
                    End If

                    Dim filechecksize As FileStream
                    filechecksize = File.Open(FileLocation, FileMode.Open)
                    If filechecksize.Length >= 25000000 Then
                        SendTweet("Cannot send file: file is larger then 25Mb, which is the file size limit of Google Mail.")
                        filechecksize.Close()
                        filechecksize.Dispose()
                        Exit Select
                    End If
                    filechecksize.Close()
                    filechecksize.Dispose()

                    SendEmail(My.Settings.GmailUserName, My.Settings.GmailPassword, (workingFolder & "\" & FileName).Trim, "Attached file by TweetMyPC")
                    SendTweet("File send as e-mail")
                Else
                    SendTweet("Email is not configured. Cannot send File")
                End If
            Case "wallpaper"
                tweet = tweet.Remove(0, splitTweet.Length)
                Do While tweet.StartsWith(" ") = True
                    tweet = tweet.Remove(0, 1)
                Loop
                Try
                    wallpaperSet(tweet)
                    SendTweet("Wallpaper set sucessfully!")
                Catch ex As Exception
                    SendTweet("setting wallpaper failed!")
                    DebugPrintHelper("setting wallpaper failed " & ex.Message)
                End Try
            Case "url"
                tweet = tweet.Remove(0, splitTweet.Length)
                Do While tweet.StartsWith(" ") = True
                    tweet = tweet.Remove(0, 1)
                Loop
                DebugPrintHelper("now try to open the url as system process start - url is: " & tweet)
                System.Diagnostics.Process.Start(tweet)
                SendTweet("URL opened!")
            Case "message"
                tweet = tweet.Remove(0, splitTweet.Length)
                Do While tweet.StartsWith(" ") = True
                    tweet = tweet.Remove(0, 1)
                Loop
                tmrTweet.Enabled = True
                SendTweet("Message to user received!")
                NotifyIcon.Text = "Program activated and waiting for new tweet..."
                DebugPrintHelper("Status changed to 'Program activated and waiting for new tweet...' because it is now going to show the message command text and the app continues running")
                Me.Focus()
                If (MessageBox.Show("Message received:" & tweet.ToString.Trim & vbCrLf & vbCrLf & "Do you want to reply to it?", "Message sent to you via TweetMyPC using Twitter", MessageBoxButtons.YesNoCancel) = Windows.Forms.DialogResult.Yes) Then
                    SendTweet("reply to message: " & InputBox("Enter your reply:", "Reply to twitter message", ""))
                Else
                    SendTweet("User closed the Message you sent earlier (no reply)!")
                End If
            Case "download"
                'Start a new thread and download the file      
                If txtDownloadLocation.Text.Trim <> "" Then
                    dwnloadThread = New Thread(AddressOf startDownload)
                    tweet = tweet.Remove(0, splitTweet.Length)
                    Do While tweet.StartsWith(" ") = True
                        tweet = tweet.Remove(0, 1)
                    Loop
                    DebugPrintHelper("Now try to start the download thread to save '" & tweet & "' to the default download location")
                    dwnloadThread.Start(CStr(tweet))
                Else
                    SendTweet("You have not configured default download location.")
                End If
            Case "print"
                tweet = tweet.Remove(0, splitTweet.Length)
                Do While tweet.StartsWith(" ") = True
                    tweet = tweet.Remove(0, 1)
                Loop
                DebugPrintHelper("now try to print: " & tweet)
                If tweet.Contains(".pdf") Then
                    printThread = New Thread(AddressOf Printing.PrintPDF)
                    printThread.Start(CStr(tweet & "|" & workingFolder))
                    SendTweet("Your file should be printing now.")
                ElseIf tweet.Contains(".doc") Then 'docx also contains "doc" ;-)
                    printThread = New Thread(AddressOf Printing.PrintDOC)
                    printThread.Start(CStr(tweet & "|" & workingFolder))
                    SendTweet("Your file should be printing now.")
                Else
                    SendTweet("Unsupported format for printing! (use pdf, doc or docx!).")
                End If
            Case "kill"
                'Kill the process
                Dim tempProc As Process
                DebugPrintHelper("now try to kill process: " & tweet.Remove(0, splitTweet.Length))
                Try
                    Dim string1 As String = tweet.Remove(0, splitTweet.Length)
                    string1 = string1.Remove(0, splitTweet.Length)
                    Do While string1.StartsWith(" ") = True
                        string1 = string1.Remove(0, 1)
                    Loop
                    tempProc = Process.GetProcessById(CInt(string1))
                    tempProc.CloseMainWindow()
                    tempProc.WaitForExit(2000)
                    SendTweet("Killed Process")
                Catch ex As Exception
                    DebugPrintHelper("Error during killing process: " & ex.Message)
                    SendTweet("Couldn't kill the process or the application could be waiting for an input. Try Screenshot or please try again. Also you might need administrator rights.")
                End Try
            Case "getfilelist"
                If My.Settings.GmailUserName = "" Then
                    SendTweet("Email is not configured. Cannot send File List")
                    Exit Sub
                End If
                DebugPrintHelper("now answer command getfilelist")

                Try
                    'Get the drive for which File List is required
                    Dim Drive As String
                    Drive = tweet.Remove(0, splitTweet.Length)
                    Do While Drive.StartsWith(" ") = True
                        Drive = Drive.Remove(0, 1)
                    Loop

                    Dim di As New IO.DirectoryInfo(Drive)
                    Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
                    Dim fi As IO.FileInfo
                    Dim arydi1 As IO.DirectoryInfo() = di.GetDirectories
                    Dim di1 As IO.DirectoryInfo

                    Dim path As String
                    path = workingFolder & "\FileList.txt"
                    If File.Exists(path) Then System.IO.File.Delete(path)
                    Dim ioFile As New StreamWriter(path)
                    For Each di1 In arydi1
                        ioFile.WriteLine(di1.Name)
                    Next
                    For Each fi In aryFi
                        ioFile.WriteLine(fi.Name)
                    Next
                    ioFile.Close()
                    'Send email
                    SendEmail(My.Settings.GmailUserName, My.Settings.GmailPassword, path, "File list by TweetMyPC")
                    ioFile.Dispose()
                    SendTweet("File list send as e-mail")
                Catch ex As Exception
                    DebugPrintHelper("exception creating and then sending FileList: " & ex.Message)
                    SendTweet("Wasn't able to generate the FileList of the Folder - please check your FolderPath or ask for help at http://tweetmypc.codeplex.com")
                End Try
        End Select
    End Sub

    Private Sub startDownload(ByVal Location As Object)
        NotifyIcon.Text = "Downloading the requested file..."
        DebugPrintHelper("Status changed to 'Downloading the requested file...'")

        Dim fileToDownload As String
        fileToDownload = CStr(Location)
        'Expant the url
        Dim wc As New WebClient
        Dim url As Uri
        Dim s As String
        Try
            '-----------------------
            If 1 = 1 Then
                MessageBox.Show("bit.ly shortener key not included in the code! - remove this message after inserting it + don't publish the sourcecode with it!!")
                Exit Sub
            End If
            '-----------------------
            url = New Uri("http://api.bit.ly/expand?version=2.0.1&shortUrl=" + fileToDownload + "&addhere")
            s = wc.DownloadString(url)

            Dim rd As New JsonTextReader(New StringReader(s))

            While rd.Read
                If rd.TokenType = JsonToken.PropertyName Then
                    If rd.Value <> "results" Then
                        rd.Skip()
                    Else
                        While rd.Read
                            If rd.TokenType = JsonToken.String Then
                                'MsgBox(rd.Value)
                                fileToDownload = rd.Value
                                Location = rd.Value
                                Exit While
                            End If
                        End While
                    End If
                End If
            End While
            rd.Close()
            fileToDownload = fileToDownload.Substring(fileToDownload.LastIndexOf("/") + 1)

            My.Computer.Network.DownloadFile(CStr(Location), txtDownloadLocation.Text + fileToDownload)
            SendTweet("Initiated Download.")
        Catch ex As Exception
            DebugPrintHelper("Download failed: " & ex.Message)
            SendTweet("Download Failed. Please check your download location.")
        End Try
        wc.Dispose()
    End Sub

    Sub SendEmail(ByVal UserName, ByVal Password, ByVal FilePath, ByVal Subject)
        NotifyIcon.Text = "Sending EMail..."
        DebugPrintHelper("Status changed to 'Sending EMail...'")
        Dim mail As MailMessage = New MailMessage
        Dim attach As New Attachment(FilePath)
        Try
            If Not UserName.ToString.EndsWith("@gmail.com") Or Not UserName.ToString.EndsWith("@googlemail.com") Then UserName = UserName + "@gmail.com"

            mail.From = New MailAddress(UserName)
            mail.To.Add(New MailAddress(UserName))
            mail.Subject = Subject
            mail.Body = "<html><body>This email was autogenerated. Please do not reply. <br><a href='http://tweetmypc.codeplex.com/'>TweetMyPC</a></body></html>"
            If FilePath <> " then" Then
                mail.Attachments.Add(attach)
            End If

            mail.IsBodyHtml = True

            Dim client As SmtpClient = New SmtpClient("smtp.gmail.com", 587)
            client.EnableSsl = True
            client.Credentials = New System.Net.NetworkCredential(UserName, Password)

            client.Send(mail)
        Catch ex As Exception
            DebugPrintHelper("sending email failed: " & ex.Message)
            SendTweet("Sending email failed. Please Try again")
        End Try
        mail.Dispose()
        attach.Dispose()
    End Sub

    Public Sub SendTweet(ByVal message As String)
        NotifyIcon.Text = "Sending tweet-respond..."
        DebugPrintHelper("Status changed to 'Sending tweet-respond...' with tweet-message: " & message.Trim)
        Try
            tw.Update((DateAndTime.TimeString.ToString & " tmPC: " & message))
        Catch ex As Exception
            DebugPrintHelper("sending tweet failed!: " & ex.Message)
        End Try
    End Sub

    Private Sub frmTweetMyPc_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If e.CloseReason = CloseReason.UserClosing Then
            If MessageBox.Show("Are you sure you want to close the program?", "End Application?", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then
                e.Cancel = True
            Else
                NotifyIcon.Visible = False
                DebugPrintHelper("App closing wanted by user.... goodbye!")
            End If
        Else
            NotifyIcon.Visible = False
            DebugPrintHelper("App closing.... goodbye! + reason:" & e.CloseReason.ToString)
        End If
        My.Settings.Save()
    End Sub

    Private Sub frmTweetMyPc_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Minimized
        Me.ShowInTaskbar = False
        DebugPrintHelper("---")
        DebugPrintHelper("---")
        DebugPrintHelper("Program starting..")
        'do the database access stuff
        databasePath = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\") + 1) & "TweetMyPC.mdb"
        If Not System.IO.File.Exists(databasePath) And Not System.IO.File.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\TweetMyPC.mdb") Then
            My.Computer.Network.DownloadFile("http://ludowicy.bplaced.net/projekte/TweetMyPC/db/TweetMyPC.mdb", System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\TweetMyPC.mdb")
            DebugPrintHelper("frmTweetMyPC_Load:: copy of database should now be created sucessfully... -> change databasePath")
        End If
        DebugPrintHelper("frmTweetMyPC_Load:: path to database in excecutionPath= " & databasePath)
        If Not hasWriteAccessToDatabase() Then
            DebugPrintHelper("frmTweetMyPC_Load:: Application doesn't have WriteAccessToDatabase -> now try to make a copy..")
            Try
                DebugPrintHelper("frmTweetMyPC_Load:: first check if there is already an accessible copy of the database available, if not -> make copy")
                If Not System.IO.File.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\TweetMyPC.mdb") Then
                    System.IO.File.Copy(databasePath, System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\TweetMyPC.mdb")
                    DebugPrintHelper("frmTweetMyPC_Load:: copy of database should now be created sucessfully... -> change databasePath")
                End If
                databasePath = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\TweetMyPC.mdb"
                DebugPrintHelper("frmTweetMyPC_Load:: databasPath changed to accessible copy at: " & databasePath)
            Catch ex As Exception

                MessageBox.Show("Not able to get Read&Write-access to the database! Please check your security settings." & vbCrLf & ex.Message)
                DebugPrintHelper("frmTweetMyPC_Load:: Not able to get Read&Write-access to the database!" & ex.Message)
                Application.Exit()
            End Try
        End If
        workingFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
        DebugPrintHelper("workingfolder: " & workingFolder & " and DatabasePath: " & databasePath)
        'populate Email settings field

        'Retriving all values from settings table and giving to settings
        con.ConnectionString = _
                "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                "Data Source=" & databasePath & ";"
        cmd.Connection = con
        Try
            con.Open()
        Catch ex As Exception
            MsgBox(ex.Message + "Sorry. Connecting to the database failed! Please try again")
            Exit Sub
        End Try


        Dim SqlAdapter As New OleDb.OleDbDataAdapter(cmd)
        Dim sqlDs As New DataSet
        cmd.CommandText = "SELECT * FROM Settings"
        cmd.ExecuteNonQuery()
        SqlAdapter.Fill(sqlDs)
        If sqlDs.Tables(0).Rows.Count <> 0 Then
            My.Settings.OAuthToken = sqlDs.Tables(0).Rows(0).Item("TwitterUserName").ToString()
            My.Settings.OAuthTokenSecret = sqlDs.Tables(0).Rows(0).Item("TwitterPassword").ToString()
            My.Settings.GmailUserName = sqlDs.Tables(0).Rows(0).Item("GmailUserName").ToString()
            My.Settings.GmailPassword = DecryptString(sqlDs.Tables(0).Rows(0).Item("GmailPassword").ToString(), P_REGISTRY_PWD)
            My.Settings.DownloadLocation = sqlDs.Tables(0).Rows(0).Item("DownloadLocation").ToString()
            Try
                tw.AuthenticateWith(My.Resources.ConsumerKey, My.Resources.ConsumerSecret, My.Settings.OAuthToken, My.Settings.OAuthTokenSecret)
            Catch ex As Exception
                DebugPrintHelper("authenticating failed at place 0001: " & ex.Message)
                MsgBox(ex.Message)
            End Try
        Else
            Me.WindowState = FormWindowState.Normal
            Me.ShowInTaskbar = True
            Me.Visible = True
        End If

        Try
            con.Close()
            cmd.Dispose()
            SqlAdapter.Dispose()
            sqlDs.Dispose()
        Catch ex As Exception
            DebugPrintHelper("error reading settings from database: " & ex.Message)
            MsgBox(ex.Message)
        End Try
        If My.Resources.ConsumerKey.Length < 10 Then
            DebugPrintHelper("code compiled without Twitter Application Authentication Key!")
            MessageBox.Show("code compiled without Twitter Application Authentication Key! app will close")
            Application.Exit()
        End If
        
        If My.Settings.hideIcon = True Then PictureBox1.Image = My.Resources.signinbutton
        tmrTweet.Enabled = True
        NotifyIcon.Text = "Program activated and waiting for new tweet..."
        DebugPrintHelper("Status changed to 'Program activated and waiting for new tweet'")
    End Sub

    Private Sub TestToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestToolStripMenuItem.Click
        tmrTweet.Enabled = False
        NotifyIcon.Text = "Checking deactivated until you close the configuration-window."
        DebugPrintHelper("Status changed to 'Checking deactivated until you close the configuration-window.'")
        txtEmailUsername.Text = My.Settings.GmailUserName
        txtEmailPassword.Text = My.Settings.GmailPassword
        If My.Settings.AutomaticStart = True Then chkStartAutomatic.Checked = True
        Me.WindowState = FormWindowState.Normal
        Me.ShowInTaskbar = True
        Me.Visible = True
    End Sub

    Private Sub NotifyIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon.MouseDoubleClick
        tmrTweet.Enabled = False
        NotifyIcon.Text = "Checking deactivated until you close the configuration-window."
        DebugPrintHelper("Status changed to 'Checking deactivated until you close the configuration-window.'")
        txtEmailUsername.Text = My.Settings.GmailUserName
        txtEmailPassword.Text = My.Settings.GmailPassword
        txtDownloadLocation.Text = My.Settings.DownloadLocation

        If My.Settings.AutomaticStart = True Then chkStartAutomatic.Checked = True

        Me.WindowState = FormWindowState.Normal
        Me.Visible = True
        Me.ShowInTaskbar = True
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        DebugPrintHelper("ExitToolStripMenuItem_Click - goodbye")
        Application.Exit()
    End Sub

    Public Sub ShowMemoryStatus()
        DebugPrintHelper("now in ShowMemoryStatus")
        Dim MemStat As New MEMORYSTATUS

        MemStat.dwLength = Len(MemStat)
        frmTweetMyPc.GlobalMemoryStatus(MemStat)
        sTotalPhys = String.Format("{0} (kb)", Format(MemStat.dwTotalPhys / 1024, "###,###"))
        sAvailPhys = String.Format("{0} (kb)", Format(MemStat.dwAvailPhys / 1024, "###,###"))

        sTotalVirtual = String.Format("{0} (kb)", Format(MemStat.dwTotalVirtual / 1024, "###,###"))
        sAvailVirtual = String.Format("{0} (kb)", Format(MemStat.dwAvailVirtual / 1024, "###,###"))
        MemStat = Nothing
    End Sub

    Public Sub SystemInfo()
        DebugPrintHelper("now in SystemInfo")
        sSysOS = String.Format("{0} - {1}", Environment.OSVersion, Environment.OSVersion.Version.Build)
        sSysUser = Environment.UserName
        sSysDomain = Environment.UserDomainName
        sSysMachine = Environment.MachineName
    End Sub

    Public Sub sendScreenshot()
        DebugPrintHelper("now in sendScreenshot")
        Dim bmpSS As Bitmap
        Dim gfxSS As Graphics
        Dim fileName As String = ""
        Dim screen_widht As Long
        Dim screen_height As Long
        Dim screen_size As Size
        Try
            For x1 As Integer = 0 To Screen.AllScreens.Length - 1
                If screen_height < Screen.AllScreens(x1).Bounds.Height Then
                    screen_height = Screen.AllScreens(x1).Bounds.Height
                End If
                screen_widht += Screen.AllScreens(x1).Bounds.Width
            Next x1
            screen_size.Height = screen_height
            screen_size.Width = screen_widht

            bmpSS = New Bitmap(screen_widht, screen_height, PixelFormat.Format32bppArgb)
            gfxSS = Graphics.FromImage(bmpSS)
            gfxSS.CopyFromScreen(0, 0, 0, 0, screen_size, CopyPixelOperation.SourceCopy)

            fileName = workingFolder + "\pic.jpeg"
            'Save File
            bmpSS.Save(fileName, ImageFormat.Jpeg)

            bmpSS.Dispose()
            gfxSS.Dispose()
        Catch ex As Exception
            DebugPrintHelper("error in sendScreenshot: " & ex.Message)
        End Try

        'Upload the file to twitpic
        'Dim twitPic As New TWITPIC.ClsTwitPic
        'twitPic.SendPicToTwitPic(My.Settings.UserName, My.Settings.Password, "Uploaded Image ", fileName)
        'tw.TweetPhotoUpload("C:\path\to\picture\test.jpg", "", "TwitterUsername", "TwitterPassword", "TweetPhotoAPIKey")

        System.IO.File.Delete(fileName)
        DebugPrintHelper("now leaving send Screenshot ")
    End Sub

    Private Sub AboutTweetMyPCToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        System.Diagnostics.Process.Start("http://tweetmypc.codeplex.com/")
    End Sub

    Private Sub HelpToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpToolStripMenuItem.Click
        System.Diagnostics.Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=39UYDW7GTXBJ8&lc=IN&item_name=TweetMyPC&item_number=TweetMyPC&currency_code=USD&bn=PP%2dDonationsBF%3aimages1%2egif%3aNonHosted")
    End Sub

    Private Sub CustomCommandToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomCommandToolStripMenuItem.Click
        DebugPrintHelper("open Custom Commands window")
        CustomCommands.ShowDialog()
        CustomCommands.Focus()
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        NotifyIcon.Text = "Checking and saving configuration..."
        DebugPrintHelper("Status changed to 'Checking and saving configuration...'")

        'Check for other settings
        If txtEmailUsername.Text.Trim <> "" Then
            If txtEmailPassword.Text.Trim = "" Then
                MsgBox("Please enter Email password.")
                txtEmailPassword.Focus()
                Exit Sub
            End If
        End If

        btnSave.Text = "Please wait..."
        Me.Refresh()
        'Save twitter user name and password, gmail user name and password in the Database
        con.ConnectionString = _
                "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                "Data Source=" & databasePath & ";"
        cmd.Connection = con

        Try
            con.Open()
            cmd = con.CreateCommand
        Catch ex As Exception
            MsgBox("Failed to connect to Database! Exception Message: " & vbCrLf & vbCrLf & ex.Message & vbCrLf & "Sorry. Please try again")
            DebugPrintHelper("Failed to connect to Database in btnSave.Click! Exception Message: " & ex.Message)
            btnSave.Text = "Save and Hide"
        End Try
        Try
            cmd.CommandText = "DELETE FROM Settings"
            cmd.ExecuteNonQuery()

        Catch ex As Exception
            MsgBox("Failed to delete all settings in settings table in Database! Exception Message: " & vbCrLf & vbCrLf & ex.Message & vbCrLf & "Sorry. Please try again")
            DebugPrintHelper("Failed to delete all settings in settings table in Database in btnSave.Click! Exception Message: " & ex.Message)
            btnSave.Text = "Save and Hide"
        End Try

        Try
            cmd.CommandText = "INSERT INTO Settings (TwitterUserName, TwitterPassword, GmailUserName, GmailPassword, DownloadLocation) VALUES ('" + My.Settings.OAuthToken + "','" + My.Settings.OAuthTokenSecret + "','" + txtEmailUsername.Text.Trim + "','" + EncryptString(txtEmailPassword.Text.Trim, P_REGISTRY_PWD) + "','" + txtDownloadLocation.Text.Trim + "')"
            cmd.ExecuteNonQuery()
            'MsgBox("Succesfully inserted")
        Catch ex As Exception
            MsgBox("Failed to write new settings to Database! Exception Message: " & vbCrLf & vbCrLf & ex.Message & vbCrLf & "Sorry. Please try again")
            DebugPrintHelper("Failed to write new settings to Database in btnSave.Click! Exception Message: " & ex.Message) 'Do not log the values because of privacy and security
            btnSave.Text = "Save and Hide"
        End Try

        Try
            con.Close()
            cmd.Dispose()
        Catch ex As Exception
            MsgBox("Failed to close and clean DatabaseConnection! Exception Message: " & vbCrLf & vbCrLf & ex.Message)
            DebugPrintHelper("Failed to close and clean DatabaseConnection in btnSave.Click! Exception Message: " & ex.Message)
            btnSave.Text = "Save and Hide"
        End Try

        If txtEmailUsername.Text.Trim <> "" Or txtDownloadLocation.Text.Trim <> "" Then
            'Save other settings
            My.Settings.GmailUserName = txtEmailUsername.Text.Trim
            My.Settings.GmailPassword = txtEmailPassword.Text.Trim
            My.Settings.DownloadLocation = txtDownloadLocation.Text
        End If
        'Minimize 
        Me.WindowState = FormWindowState.Minimized
        Me.Visible = False
        Me.ShowInTaskbar = False
        tmrTweet.Enabled = True
        btnSave.Text = "Save and Hide"
        NotifyIcon.Text = "Program activated and waiting for new tweet..."
        DebugPrintHelper("Status changed to 'Program activated and waiting for new tweet...'")
    End Sub

    Private Sub LinkLabel2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
        System.Diagnostics.Process.Start("http://tweetmypc.codeplex.com/")
    End Sub

    Public P_REGISTRY_PWD As String = "TweetMyPC"

    'Private

    Shared Function Encrypt(ByVal strText As String, ByVal strEncrKey As String) As String

        Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}

        Try

            Dim byteKey() As Byte = System.Text.Encoding.UTF8.GetBytes(strEncrKey, 0, 8)

            Dim byteArrayInput() As Byte = System.Text.Encoding.UTF8.GetBytes(strText)

            Dim des As New System.Security.Cryptography.DESCryptoServiceProvider

            Dim ms As New MemoryStream

            Dim cs As New System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(byteKey, IV), System.Security.Cryptography.CryptoStreamMode.Write)
            cs.Write(byteArrayInput, 0, byteArrayInput.Length)

            cs.FlushFinalBlock()


            Return Convert.ToBase64String(ms.ToArray())

        Catch ex As Exception

            Return ex.Message

        End Try

    End Function

    Private Shared Function Decrypt(ByVal strText As String, ByVal strDecrKey As String) As String

        Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}

        Dim inputByteArray(strText.Length) As Byte

        Try

            Dim byteKey() As Byte = System.Text.Encoding.UTF8.GetBytes(strDecrKey, 0, 8)

            Dim des As New System.Security.Cryptography.DESCryptoServiceProvider
            inputByteArray = Convert.FromBase64String(strText)


            Dim ms As New MemoryStream

            Dim cs As New System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(byteKey, IV), System.Security.Cryptography.CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)

            cs.FlushFinalBlock()


            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8

            Return encoding.GetString(ms.ToArray())

        Catch ex As Exception

            Return ex.Message

        End Try

    End Function
    Public Function DecryptString(ByVal sEncryptSetting As String, ByVal strEncrKey As String) As String
        '-----------------------
        If 1 = 0 Then
            MessageBox.Show("DecryptSetting not included in the code! - remove this message after inserting it + don't publish the sourcecode with it!!")
            Return sEncryptSetting
        End If
        '-----------------------
        Return sEncryptSetting
    End Function

    Public Function EncryptString(ByVal sEncryptSetting As String, ByVal strEncrKey As String) As String
        '-----------------------
        If 1 = 0 Then
            MessageBox.Show("EncryptSetting not included in the code! - remove this message after inserting it + don't publish the sourcecode with it!!")
            Return sEncryptSetting
        End If
        '-----------------------
        Return sEncryptSetting
    End Function

    Public Function GetIpAddress() As String
        DebugPrintHelper("now in GetIpAddress")
        Try
            Dim req As HttpWebRequest = WebRequest.Create("http://automation.whatismyip.com/n09230945.asp")
            Dim res As HttpWebResponse = req.GetResponse()
            Dim Stream As Stream = res.GetResponseStream()
            Dim sr As StreamReader = New StreamReader(Stream)
            Return sr.ReadToEnd()
        Catch ex As Exception
            DebugPrintHelper("Error getting the ip: " + ex.Message.Trim)
            Return "error/invalid!"
        End Try
    End Function

    Private Sub tbnPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbnPath.Click
        Try
            Dim bolContinue As Boolean = False
            Do Until bolContinue = True
                Dim folderbrowserDialog As New FolderBrowserDialog
                folderbrowserDialog.Description = "Please select the folder where you want to save downloaded files."
                folderbrowserDialog.SelectedPath = txtDownloadLocation.Text
                folderbrowserDialog.ShowDialog()
                If folderbrowserDialog.SelectedPath <> "" Then
                    txtDownloadLocation.Text = folderbrowserDialog.SelectedPath
                    If Not hasWriteAccessToFolder(txtDownloadLocation.Text) Then
                        MsgBox("You don't have write-access to this folder! Please select another folder!", MsgBoxStyle.Critical, "No write access!!")
                        bolContinue = False
                    Else
                        bolContinue = True
                    End If
                End If
                folderbrowserDialog.Dispose()
            Loop
        Catch ex As Exception
            DebugPrintHelper("tbnPath_Click exception: " & ex.Message)
            MsgBox("An error has ocurred: " + ex.Message)
        End Try
    End Sub

    Public Function hasWriteAccessToFolder(ByVal folderPath) As Boolean
        DebugPrintHelper("now in hasWriteAccessToFolder")
        Dim TextFile As FileStream
        Try
            ' Attempt to get a list of security permissions from the folder.  
            ' This will raise an exception if the path is read only or do not have access to view the permissions.  
            Dim ds As System.Security.AccessControl.DirectorySecurity = Directory.GetAccessControl(folderPath)

            'the following code-part checks if there is any rule that denies access to the folder
            Dim collection As System.Security.AccessControl.AuthorizationRuleCollection = Directory.GetAccessControl(folderPath).GetAccessRules(True, True, GetType(System.Security.Principal.NTAccount))
            For Each rule As System.Security.AccessControl.FileSystemAccessRule In collection
                If rule.AccessControlType = System.Security.AccessControl.AccessControlType.Deny Then
                    Return False
                    Exit Function
                End If
            Next
            '---------------
            'there is still the possibility that none of the directoryaccess-rules allows you access to the directory, so test it by writing and then undoing the changes to the directory - but the application first checked the directory-permissions because it is much faster...

            TextFile = File.Create(folderPath & "\fjubruehfhrbfhbdfhebhfbezh75hfh75hgb47745nb754b7.txt")
            If Not TextFile.CanWrite = True Then
                Throw New Exception
            End If
            TextFile.WriteByte(4)
            TextFile.Close()
            If File.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\VirtualStore" & folderPath.ToString.Remove(0, 2) & "\fjubruehfhrbfhbdfhebhfbezh75hfh75hgb47745nb754b7.txt") Then

                Throw New Exception 'If it is in the VirtualStore, then the program doesn't have write access to the in the dialog selected folder... ;-)
            End If
            If Not File.Exists(folderPath & "\fjubruehfhrbfhbdfhebhfbezh75hfh75hgb47745nb754b7.txt") Then
                Throw New Exception
            End If
            File.Delete(folderPath & "\fjubruehfhrbfhbdfhebhfbezh75hfh75hgb47745nb754b7.txt")

            Return True
        Catch ex As Exception
            If File.Exists(folderPath & "\fjubruehfhrbfhbdfhebhfbezh75hfh75hgb47745nb754b7.txt") Then File.Delete(folderPath & "\fjubruehfhrbfhbdfhebhfbezh75hfh75hgb47745nb754b7.txt") 'will also delete the file if it is in the VirtualStore
            Return False
        End Try
        TextFile.Dispose()
    End Function

    Public Function hasWriteAccessToDatabase() As Boolean
        DebugPrintHelper("now in hasWriteAccessToDatabase")
        Try
            ' Attempt to get a list of security permissions from the file.  
            ' This will raise an exception if the path is read only or do not have access to view the permissions.
            ' see http://msdn.microsoft.com/en-us/library/0927za87.aspx for help
            Dim ds As System.Security.AccessControl.FileSecurity = File.GetAccessControl(databasePath)

            'the following code-part checks if there is any rule that denies access to the database
            Dim collection As System.Security.AccessControl.AuthorizationRuleCollection = File.GetAccessControl(databasePath).GetAccessRules(True, True, GetType(System.Security.Principal.NTAccount))
            For Each rule As System.Security.AccessControl.FileSystemAccessRule In collection
                If rule.AccessControlType = System.Security.AccessControl.AccessControlType.Deny Then
                    Return False
                    Exit Function
                End If
            Next
            '---------------

            'there is still the possibility that none of the fileaccess-rules allows you access to the file, so test it by writing and then undoing the changes to the database - but the application first checked the file-permissions because it is much faster...
            con.ConnectionString = _
                "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                "Data Source=" & databasePath & ";"
            cmd.Connection = con
            con.Open()
            cmd = con.CreateCommand
            cmd.CommandText = "CREATE TABLE customer (First_Name char(50), Last_Name char(50))"
            cmd.ExecuteNonQuery()
            cmd.CommandText = "DROP TABLE customer"
            cmd.ExecuteNonQuery()
            con.Close()
            cmd.Dispose()
            '---------------
            Return True

        Catch ex As Exception
            If con.State = ConnectionState.Open Or con.State = ConnectionState.Broken Then 'the check for broken if for net.framework 3.5 and 4...
                con.Close()
                cmd.Dispose()
            End If
            Return False
        End Try
    End Function

    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer)

    Private Sub LicenseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LicenseToolStripMenuItem.Click
        System.Diagnostics.Process.Start("http://tweetmypc.codeplex.com/license")
    End Sub

    Private Sub HelpToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpToolStripMenuItem1.Click
        System.Diagnostics.Process.Start("http://tweetmypc.codeplex.com/wikipage?title=installation_guide")
    End Sub

    Public Sub DebugPrintHelper(ByVal printString As String)
        Try
            Debug.WriteLine(printString.Trim)
            If System.IO.File.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\TweetMyPCdebug.txt") Then
                File.AppendAllText(System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\TweetMyPCdebug.txt", DateAndTime.Now.ToString.Trim & "    " & printString.Trim & vbCrLf)
            End If
        Catch ex As Exception
        End Try
    End Sub

    Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" (ByVal uAction As Integer, ByVal uParam As Integer, ByVal lpvParam As Integer, ByVal fuWinIni As Integer) As Integer
    Public Function ToggleScreenSaverActive(ByRef Active As Boolean) As Boolean
        DebugPrintHelper("now in ToggleScreenSaverActive")
        Dim lActiveFlag As Integer
        Dim retvaL As Integer
        lActiveFlag = IIf(Active, 1, 0)
        retvaL = SystemParametersInfo(17, lActiveFlag, 0, 0)
        ToggleScreenSaverActive = retvaL > 0
    End Function

    <System.Runtime.InteropServices.DllImport("user32.dll")> _
    Private Shared Function SendMessage(ByVal hWnd As Integer, ByVal hMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    End Function
    Public Sub darken_change()
        DebugPrintHelper("now in darken_change")
        SetWindowLong(Handle, -20, GetWindowLong(Handle, -20) Or &H80)
        SendMessage(&HFFFF, &H112S, &HF170, 2)
    End Sub
    <System.Runtime.InteropServices.DllImport("user32.dll")> _
    Public Shared Function SetWindowLong(ByVal window As IntPtr, ByVal index As Integer, ByVal value As Integer) As Integer
    End Function
    <System.Runtime.InteropServices.DllImport("user32.dll")> _
    Public Shared Function GetWindowLong(ByVal window As IntPtr, ByVal index As Integer) As Integer
    End Function

    Private Declare Function SystemParametersInfo Lib "user32.dll" Alias "SystemParametersInfoA" (ByVal uAction As Integer, ByVal uParam As Integer, ByVal lpvParam As String, ByVal fuWinIni As Integer) As Integer
    Private Const SPI_SETDESKWALLPAPER = 20
    Private Const SPIF_UPDATEINIFILE = &H1
    Sub wallpaperSet(ByVal URL As String)
        DebugPrintHelper("now in wallpaperSet")
        Try
            Dim imagePath As String = workingFolder & "\Wallpaper.bmp"
            Dim bmp1 As New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(URL)))
            Dim pic As New PictureBox
            pic.Image = bmp1
            pic.Image.Save(imagePath, ImageFormat.Bmp)
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imagePath, SPIF_UPDATEINIFILE)
            bmp1.Dispose()
            pic.Dispose()
        Catch ex As Exception
            DebugPrintHelper("exception in wallpaperSet: " & ex.Message & "|||||||" & ex.InnerException.Message)
        End Try
        DebugPrintHelper("leaving wallpaperSet")
    End Sub

    Private Const APPCOMMAND_VOLUME_MUTE As Integer = &H80000
    Private Const APPCOMMAND_VOLUME_UP As Integer = &HA0000
    Private Const APPCOMMAND_VOLUME_DOWN As Integer = &H90000
    Private Const WM_APPCOMMAND As Integer = &H319

    <System.Runtime.InteropServices.DllImport("user32.dll")> _
    Public Shared Function SendMessageW(ByVal hWnd As IntPtr, _
           ByVal Msg As Integer, ByVal wParam As IntPtr, _
           ByVal lParam As IntPtr) As IntPtr
    End Function
    Private Sub VolMute()
        SendMessageW(Me.Handle, WM_APPCOMMAND, _
                      Me.Handle, New IntPtr(APPCOMMAND_VOLUME_MUTE))
    End Sub
    Private Sub VolDec()
        SendMessageW(Me.Handle, WM_APPCOMMAND, _
                     Me.Handle, New IntPtr(APPCOMMAND_VOLUME_DOWN))
    End Sub
    Private Sub VolInc()
        SendMessageW(Me.Handle, WM_APPCOMMAND, _
                     Me.Handle, New IntPtr(APPCOMMAND_VOLUME_UP))
    End Sub

    Public Sub CheckForUpdate() 'this is death now, just used in versions older then v3.5 - don't delete this because this is an educational app ;-)
        DebugPrintHelper("now in CheckForUpdate")
        Dim client As WebClient = New WebClient()
        Try
            Dim reply As String = client.DownloadString("http://basisbit.de/projekte/TweetMyPC/version.php")
            If reply > 300 Then
                DebugPrintHelper("New version available: " & reply.Trim)
                If MessageBox.Show("New version available!" & vbCrLf & "Do you want to download the new version now?", "Download new version", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
                    System.Diagnostics.Process.Start("http://tweetmypc.codeplex.com")
                    NotifyIcon.Visible = False
                    Application.Exit()
                End If
            Else
                MessageBox.Show("You already have the newest version installed!", "No update available!", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            DebugPrintHelper("Error getting version-number! " + ex.Message.Trim)
            MsgBox("Error getting version-number! " + ex.Message.Trim)
        End Try
        client.Dispose()
    End Sub

    Private Sub chkShowinnotifyarea_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkShowinnotifyarea.CheckedChanged
        If chkShowinnotifyarea.Checked = True Then
            NotifyIcon.Visible = True
        Else
            NotifyIcon.Visible = False
            MsgBox(String.Format("To show this window again tweet {0}showwindow{1}.", ControlChars.Quote, ControlChars.Quote), MsgBoxStyle.OkOnly, "Hiding from notification area")
            SendTweet(String.Format("To show this window again tweet {0}showwindow{1}.", ControlChars.Quote, ControlChars.Quote))
        End If
    End Sub

    Private Sub SendTestTweet_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendTestTweet.Click
        Try
            Dim str As String = InputBox("Tweet to send", "Send a test tweet")
            tw.Update(str)
        Catch ex As Exception
            DebugPrintHelper("exception in SendTestTweet_Click")
        End Try
    End Sub

    Public Sub CheckForWebConnection()
        DebugPrintHelper("now in CheckForWebConnection")
        If My.Computer.Network.IsAvailable Then
            NotifyIcon.Icon = My.Resources.twitterOnline
            DebugPrintHelper("IsAvailable")
        Else
            NotifyIcon.Icon = My.Resources.twitterOffline
            DebugPrintHelper("IsNotAvailable")
        End If
    End Sub

    Private Sub listofcommandsToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listofcommandsToolStripMenuItem1.Click
        System.Diagnostics.Process.Start("http://tweetmypc.codeplex.com/wikipage?title=Commands")
    End Sub

    Private Sub ExitTweetMyPCToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitTweetMyPCToolStripMenuItem.Click
        If MessageBox.Show("Are you sure you want to close the program?", "End Application?", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
            NotifyIcon.Visible = False
            DebugPrintHelper("App closing wanted by user.... goodbye!")
            Application.Exit()
        End If
    End Sub

    Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
        Dim pinText As String
        MessageBox.Show("TweetMyPC will now open a Twitter Website where you have to allow access for your Twitter-Account, so that TweetMyPC will be able to answer to your tweets/commands securely." & vbCrLf & _
                        "You also need to copy the PIN which you will see after allowing TweetMyPC.", "Secure Authorization", MessageBoxButtons.OK, MessageBoxIcon.Information)
        DebugPrintHelper("TweetMyPC will now open a Twitter Website where you have to allow access for your Twitter-Account, so that TweetMyPC will.......")
        Try
            System.Diagnostics.Process.Start(tw.GetAuthorizationLink(My.Resources.ConsumerKey, My.Resources.ConsumerSecret))
        Catch twex As TwitterAPIException
            If twex.InnerException.Message = "The remote server returned an error: (401) Unauthorized." Or twex.InnerException.Message.Contains(" (401) ") Then
                MessageBox.Show("Can't verify with Twitter.com." & vbCrLf & _
                "Please open your Webbrowser and login with your Username and Password, then retry.", "(401) Unauthorized", MessageBoxButtons.OK, MessageBoxIcon.Information)
                DebugPrintHelper("Please open your Webbrowser and login with your Username and Password, then retry.(401) Unauthorized")
                Exit Sub
            Else
                DebugPrintHelper("An error happened in [try1]:catch1! Please report this problem to the developer team!" & vbCrLf & twex.Message & vbCrLf & twex.InnerException.Message)
                MessageBox.Show("An error happened in [try1]:catch1! Please report this problem to the developer team!" & vbCrLf & twex.Message & vbCrLf & twex.InnerException.Message)
            End If
        Catch ex As Exception
            DebugPrintHelper("An exception happened in PictureBox1_Click [try1]: " & ex.Message & "||||" & ex.InnerException.Message)
            MessageBox.Show("An error happened in [try1]:catch2! Please report this problem to the developer team!" & vbCrLf & ex.Message & vbCrLf & ex.InnerException.Message)
        End Try
        DebugPrintHelper("done with [try1] in PictureBox1_Click")
        Try
            DebugPrintHelper("[try2]:1")
            Sleep(3500)
            pinText = InputBox("Please enter the PIN which you got from the before opened website:", "Enter PIN for Authorization")
            DebugPrintHelper("[try2]:x" & pinText)
            Do While pinText.EndsWith(" ")
                pinText = pinText.Remove(pinText.Length - 1, 1)
            Loop
            DebugPrintHelper("[try2]:2")
            If pinText = "" Then Exit Sub
            DebugPrintHelper("[try2]:3")
            Dim IsValid As Boolean = tw.ValidatePIN(pinText)
            If IsValid Then
                DebugPrintHelper("ping seems to be valid")
                My.Settings.OAuthToken = tw.OAuth_Token()
                My.Settings.OAuthTokenSecret = tw.OAuth_TokenSecret()
            Else
                PictureBox1.Image = My.Resources.signinbutton
                MessageBox.Show("The PIN seems to be wrong, please try again")
                Exit Sub
            End If
            tw.AuthenticateWith(My.Resources.ConsumerKey, My.Resources.ConsumerSecret, My.Settings.OAuthToken, My.Settings.OAuthTokenSecret)
            ProcessTweet("Hello World - TweetMyPC is working and authorized.")
            My.Settings.hideIcon = True
            PictureBox1.Image = My.Resources.signinbuttongrey
        Catch ex As Exception
            DebugPrintHelper("An exception happened in PictureBox1_Click [try2]: " & ex.Message & "||||" & ex.InnerException.Message)
            MessageBox.Show("An error happened in [try2]:catch! Please report this problem to the developer team!" & vbCrLf & ex.Message & vbCrLf & ex.InnerException.Message)

        End Try
        DebugPrintHelper("done with [try1] in PictureBox1_Click")
    End Sub

    Private Sub CleanSettingsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CleanSettingsToolStripMenuItem.Click
        If MessageBox.Show("Are you sure you want to delete all your settings and custom commands from TweetMyPC?", "Reset?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
            FileIO.FileSystem.DeleteFile(databasePath)
            DebugPrintHelper("Database deleted")
            MessageBox.Show("TweetMyPC will reopen now!")
            Application.Restart()
        End If
    End Sub

    Private Sub TestToolStripMenuItem1_Click(sender As System.Object, e As System.EventArgs) Handles TestToolStripMenuItem1.Click
        MessageBox.Show("TweetMyPC will now tweet a testmessage!")
        SendTweet("*waking up..* yes, I am alive! See http://www.dilbert.com/fast ! ;-)")
    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem1.Click
        Me.Width = 950
    End Sub

    Private Sub CheckForUpdateToolStripMenuItem_Click_1(sender As System.Object, e As System.EventArgs) Handles CheckForUpdateToolStripMenuItem.Click
        DebugPrintHelper("now checking for update")
        GuiFunctions.InstallUpdateSyncWithInfo()
        DebugPrintHelper("checking for update done.")
    End Sub
End Class